import React from 'react'
import { View, Text, ScrollView } from 'react-native'
import { Grid } from 'antd-mobile-rn'
import { sportItems } from "./config"
import { getUser } from "../Util/UserManager"
import { getFinance, addHistory } from "../Services/FinanceService"
import { getOrganization } from "../Services/UserService"
import { generateNewHistory } from "../Util/FinanceManager"

export default class Sport extends React.Component {
    static navigationOptions = ({ navigation }) => ({
        title: `打卡`
    })

    constructor() {
        super()
        this.state = {
            user: {},
            organization: {},
            finance: {}
        }
    }

    componentWillMount = () => {
        this.getData()
    }

    getData = async () => {
        try {
            const user = await getUser()
            const organization = await getOrganization(user.organizationId)
            this.setState({ user, organization }, () => this.getFinanceData())
        } catch (error) {
            alert("获取资金失败！")
        }
    }

    getFinanceData = async () => {
        const { organization } = this.state
        const finance = await getFinance(organization.financeId)
        this.setState({ finance })
    }

    onItemClick = async (obj, index) => {
        const { user, finance } = this.state
        let decrease = await generateNewHistory(obj.money, obj.level, obj.lower)
        decrease = finance.remain < decrease ? finance.remain : decrease
        const remain = finance.remain - decrease
        const data = {
            financeId: finance._id,
            userId: user._id,
            decrease: decrease,
            remain: remain
        }
        await addHistory(data)
        this.getFinanceData()
    }

    render() {
        const { finance } = this.state
        const remain = finance.remain
        const total = finance.total
        return (
            <ScrollView>
                <Text>运动打卡</Text>
                <View>
                    <Text>总额度：</Text>
                    <Text>{total}</Text>
                </View>
                <View>
                    <Text>已获取额度：</Text>
                    <Text>{total - remain}</Text>
                </View>
                <View>
                    <Text>剩余额度：</Text>
                    <Text>{remain}</Text>
                </View>
                <Text>打卡项</Text>
                <Grid data={sportItems} columnNum={3} onClick={this.onItemClick} />
            </ScrollView>
        )
    }
}